import serial
import keyboard
import time

bluetooth_port = "COM5"
baudrate = 115200

try:
    bluetooth = serial.Serial(bluetooth_port, baudrate, timeout=0.1)  # 缩短超时为0.1秒
    print(f"已连接蓝牙串口: {bluetooth_port}")
    buffer = ""  # 用于拼接不完整的数据

    while True:
        # 读取缓冲区中所有可用数据
        if bluetooth.inWaiting() > 0:
            # 读取原始字节并解码，允许错误处理
            data_bytes = bluetooth.read(bluetooth.inWaiting())
            buffer += data_bytes.decode('utf-8', errors='replace')  # 替换错误字符
            
            # 按换行符分割完整数据
            lines = buffer.split('\n')
            # 最后一个元素可能是不完整的行，留到下次处理
            buffer = lines.pop()
            
            # 处理完整的行
            for line in lines:
                line = line.strip()
                if line:  # 过滤空行
                    print(f"收到数据: {line}")
        
        # 键盘事件处理
        if keyboard.is_pressed('q'):
            print('退出程序')
            break 
        elif keyboard.is_pressed('s'):
            message = 's\n'  # 建议加换行符，与ESP32协议一致
            bluetooth.write(message.encode('utf-8'))
            print("发送: s")
        
        # 微小延迟，降低CPU占用
        # time.sleep(0.001)

except serial.SerialException as e:
    print(f"串口错误: {e}")
except KeyboardInterrupt:
    print("程序终止")
finally:
    if 'bluetooth' in locals() and bluetooth.is_open:
        bluetooth.close()